package demo1;


public class HashBuck2<K, V> {
    static class Node<K, V> {
        public K key;
        public V val;
        public Node<K, V> next;

        public Node(K key, V val) {
            this.key = key;
            this.val = val;
        }
    }

    public Node<K, V>[] array;
    public int usedSize;
    //写法与源码相同
    public static final float DEFAULT_LOAD_FACTOR = 0.75f;

    public HashBuck2() {
        array = (Node<K, V>[])new Node[10];//写法与源码相同
    }

    public void put(K key, V val) {
        //传过来的K如果是引用类型或者字符串类型，调用hashCode方法，获得哈希值用来进行哈希计算
        //如果没有重写，默认Object的hashCode; 如果重写，调用重写后的hashCode
        int hash = key.hashCode();
        int index = hash % array.length;

        Node<K, V> prev = null;
        Node<K, V> cur = array[index];
        while (cur != null) {
            if (key.equals(cur.key)) {
                //更新val
                cur.val = val;
                return;
            }
            prev = cur;
            cur = cur.next;
        }
        Node<K, V> node = new Node<>(key, val);
        //尾插法
        if (array[index] == null) {
            array[index] = node;
            usedSize++;
            return;
        }
        prev.next = node;
        usedSize++;

        //下面计算负载因子
        //扩容，重新哈希计算
    }

    public V getValue(K key) {
        int hash = key.hashCode();
        int index = hash % array.length;
        Node<K, V> cur = array[index];
        while (cur != null) {
            if (key.equals(cur.key)) {
                return cur.val;
            }
            cur = cur.next;
        }
        return null;
    }
}










